using System;
using System.ComponentModel.Composition;
using System.Windows.Input;
using Red.Controls.Shell;
using Red.Controls.ViewModels;
using Red.Core;
using Red.EngineData.View;

namespace Red.Toolkit.PresentationEditor
{
    [Export( typeof( IEditorInfo ) )]
    public class EditorInfo : IEditorInfo
    {
        public string Name
        {
            get { return "Prefab Editor"; }
        }

        public Type WindowClass
        {
            get { return typeof( PresentationEditor ); }
        }

        public Type SettingsClass
        {
            get { return typeof( PresentationSettings ); }
        }
    }

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class PresentationEditor : RedEditorWindow
    {
        private string _prefabDir;

        public PresentationEditor( IEditorHost host, EditorInstanceData instanceData, EditorSharedData sharedData )
            : base( host, instanceData, sharedData )
        {
            InitializeComponent();

            // _prefabDir needs to be an absolute path, we need to find the entryPoint under which this resource is present
            string absolutePath = SharedData.DepotInfo.GetAbsolutePath( InstanceData.InstanceContext );
            _prefabDir = System.IO.Path.GetDirectoryName( absolutePath );
        }

        private async void MakeUnique_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            InteropTreeItem prefabTreeItem = e.Parameter as InteropTreeItem;

            // TODO: this should be replaced with general SaveAs control
            var name = TextInputDialog.Show(this, "", "Presentation name", "Create new presentation");
            if( name == null || name.Length == 0 )
            {
                return;
            }

            name = System.IO.Path.ChangeExtension(name, ".vt");
            var path = TextInputDialog.Show(this, _prefabDir, "Save in", "Create new presentation", true);
            if ( path == null || path.Length == 0 )
            {
                return;
            }
            
            var dstPath = System.IO.Path.Combine(path, name);
            var srcPath = await prefabTreeItem.ExecuteAsync<string>( "prefabPath" );

            Result result = await SharedData.ResourceFactory.SaveAs( srcPath.Value, dstPath );
            if (!result)
            {
                await ShowErrorAsync(result.Message);
				return;
            }
            // -- end of TODO

            prefabTreeItem.Execute( Interop.Make( "makeUnique({0})", SharedData.DepotInfo.GetDepotPath( dstPath ) ) );
        }
    }
}
